package com.qianfeng.zhangwei.day46.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.qianfeng.zhangwei.day46.R;
import com.qianfeng.zhangwei.day46.bean.UpdateInfo;

import java.io.File;
import java.io.InputStream;

/**
 * @说 明：
 * @项目名称：1506adc
 * @包 名： com.qianfeng.zhangwei.day39
 * @类 名：UpdateManger
 * @创 建人：zhangwei
 * @创建时间：2015-07-04 11 : 31
 * @版 本：v1.0
 * @修 改人：
 * @修改时间：
 * @修改备注：
 */
public class UpdateManger {
    private static final String updateUrl = "https://raw.githubusercontent.com/snowdream/android-autoupdate/master/docs/test/updateinfo.xml";
    private static UpdateManger updateManger;


    private static Context context;

    private String downPath;


    private UpdateManger() {

    }

    public static void init(Activity activity) {

    }


    public static UpdateManger getInstance(Context context) {
        if (updateManger == null) {
            updateManger = new UpdateManger();
            UpdateManger.context = context;
        }
        return updateManger;
    }

    private void down(String url) {
        HttpUtils utils = new HttpUtils();

        utils.download(url, downPath, new RequestCallBack<File>() {


            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                //调用安装
                install();
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    /**
     * 检查版本升级
     */
    public void update() {
        new UpdateTask().execute(updateUrl);

    }


    private class UpdateTask extends AsyncTask<String, Void, UpdateInfo> {


        @Override
        protected UpdateInfo doInBackground(String... params) {
            UpdateInfo info = null;
            InputStream inputStream = HttpTools.checkUpdate(params[0]);
            if (inputStream != null) {
                info = UpdateInfo.parseXMl(inputStream);
            }
            return info;
        }

        @Override
        protected void onPostExecute(final UpdateInfo updateInfo) {
            super.onPostExecute(updateInfo);
            if (updateInfo != null) {
                //服务器版本号
                int versionCode = Integer.valueOf(updateInfo.getVersionCode());
                if (versionCode != getVersionCode()) {

                    new AlertDialog.Builder(context)
                            .setTitle("版本升级")
                            .setIcon(R.mipmap.ic_launcher)
                            .setMessage(updateInfo.getUpdateTips().get("zh"))
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    down(updateInfo.getApkUrl());
                                }
                            })
                            .create()
                            .show();

                }

            }
        }
    }

    /**
     * 本地应用的版本号
     */

    private int getVersionCode() {
        int versionCode = 0;
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo info = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;

    }

    /**
     * 安装
     *
     * @param
     */
    public void install() {
        // 核心是下面几句代码
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(downPath)),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

}
